<template>
  <div class="login-wrap" v-wechat-title="'登陆'">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" label-position="top" class="login-form">
      <h2>用户登录</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input type="password" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
      </el-form-item>
      <el-form-item >
        <el-button class="login-btn" type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Layout from "@/views/layout/Layout";
export default {
  name: "Login",
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
        grant_type: 'password',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('goLogin',this.ruleForm).then( res =>{
            const { code,msg } = res
            if(code === "00000"){
              //获取登录用户信息
              this.$store.dispatch('getUserInfo').then( res => {
                if (res.status){
                  this.$message.success("登陆成功");
                  this.$router.push('/dashboard');
                }else {
                  this.$message.success("登陆失败，请重新登录");
                  this.$router.push('/login');
                }
              })
            }else {
              this.$message.error(msg);
            }
          })
        } else {
          return false;
        }
      });
    },
  },
  created() {
    if (this.$store.state.tags.visitedViews.length > 0){
      window.location.reload()
    }
  }
}
</script>

<style scoped>
.login-wrap{
  height: 100%;
  background-color: #324152;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-wrap .login-form{
  width: 400px;
  background-color: #fff;
  border-radius: 5px;
  padding: 30px;
}
.login-wrap .login-btn{
  width: 100%;
}
</style>
